package org.aceor.mddal.config.datasource;

import com.google.common.collect.Maps;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by lxue on 16/3/27.
 */
@XStreamAlias("conf")
public class DsConfig {
    private List<GroupNode> groups;

    @XStreamImplicit(itemFieldName = "atom")
    private List<Atom> atoms;

    private Map<String, Atom> atomMap;

    private Map<String, GroupNode> groupMap;

    public List<GroupNode> getGroups() {
        return groups;
    }

    public void setGroups(List<GroupNode> groups) {
        this.groups = groups;
    }

    public List<Atom> getAtoms() {
        return atoms;
    }

    public void setAtoms(List<Atom> atoms) {
        this.atoms = atoms;
    }

    public void init() {
        initAtomMap();
        initGroupMap();
    }

    public Map<String, Atom> getAtomMap() {
        return atomMap;
    }

    public Map<String, GroupNode> getGroupMap() {
        return groupMap;
    }

    private void initAtomMap() {
        if (CollectionUtils.isNotEmpty(atoms)) {
            if (null == atomMap) {
                atomMap = Maps.newHashMap();
            }
            for (Atom atom : atoms) {
                atomMap.put(atom.getId(), atom);
            }
        }
    }

    private void initGroupMap() {
        if (CollectionUtils.isNotEmpty(groups)) {
            if (null == groupMap) {
                groupMap = Maps.newHashMap();
            }
            for (GroupNode groupNode : groups) {
                groupMap.put(groupNode.getId(), groupNode);
            }
        }
    }

    public boolean containsAtom(String atomId) {
        return getAtomMap().containsKey(atomId);
    }

    public Atom getAtom(String atomId) {
        return getAtomMap().get(atomId);
    }

    public boolean containsGroup(String groupId){
        return getGroupMap().containsKey(groupId);
    }

    public GroupNode getGroupNode(String groupId) {
        return getGroupMap().get(groupId);
    }

    public boolean isGroupEmpty(){
        return getGroupMap().isEmpty();
    }
}
